package com.example.spider.proxy.core;

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 代理服务器认证
 */
public class ProxyAuthenticator extends Authenticator {

    public static final ProxyAuthenticator INSTANT = new ProxyAuthenticator();

    private final ConcurrentHashMap<String, PasswordAuthentication> pwdMap = new ConcurrentHashMap<>();

    public static ProxyAuthenticator getInstance() {
        return INSTANT;
    }

    /**
     * 构造
     *
     * @param username 用户名
     * @param pass 密码
     */
    public void addIfAbsent(String ip, int port, String username, String pass) {
        pwdMap.computeIfAbsent(ip + ":" + port, k -> new PasswordAuthentication(username, pass.toCharArray()));
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return pwdMap.get(getRequestingHost() + ":" + getRequestingPort());
    }

}